<template>
  <div class="home">
    <div class="header">导航栏</div>
    <virtual-scroll 
    class="virtual-scroll"
    :source-data-list="newsList"
    :one-data-height="100"
    @scroll-last="getNewsList"
    @scroll="scrollHandler"
    :scroll-last-flag="true"
    :scroll-flag="true"
    ref="vscroll">
      <template v-slot:default="slotProps">
        <news-item :news-item="slotProps.row"></news-item>
      </template>
    </virtual-scroll>
    <div class="back-top" @click="backTopClick" v-show="isShow">
      <img :src="backTopImg" alt="">
    </div>
  </div>
</template>

<script>
import NewsItem from '@/components/context/NewsItem.vue'
import backTopImg from '@/assets/img/backtop.png'
export default {
  name: 'Home',
  components: {
    NewsItem
  },
  data(){
    return {
      // 新闻列表
      newsList: [],
      // 返回顶部图片
      backTopImg,
      // 返回顶部按钮是否显示
      isShow: false,
      // 保存滚动位移
      scrollY: 0
    }
  },
  created(){
    this.getNewsList()
  },
  activated(){
    // 返回本路由时跳转到之前保存的滚动位置
    this.$refs.vscroll.scrollTo(this.scrollY);
  },
  deactivated(){
    // 跳转别的路由前保存滚动位移
    this.scrollY = this.$refs.vscroll.scrollOffset();
  },
  methods:{
    // 获取新闻列表
    getNewsList(){
      // $http为加在Vue原型上的axios
      this.$http('http://localhost:4000/news?num=30').then(res => {
        this.newsList = [...this.newsList, ...res.data.list];
      }).catch(err => {
        console.log(err)
      })
    },
    // 返回顶部事件处理
    backTopClick(){
      this.$refs.vscroll.scrollTo(0, 100);
    },
    // 滚动事件处理
    scrollHandler(val){
      this.isShow = val > 1000 ? true : false;
    }
  }
}
</script>
<style lang="less" scoped>
.home{
  height: 100%;
  display: flex;
  flex-direction: column;
  .header{
    height: 45px;
    line-height: 45px;
    background-color:tomato;
    text-align: center;
  }
  // 设置虚拟滚动可视区域范围
  .virtual-scroll{
    flex: 1;
  }
  .back-top{
    position: fixed;
    right: 15px;
    bottom: 25px;
    width: 30px;
    height: 30px;
    z-index: 9;
    img{
      width: 100%;
      height: 100%;
    }
  }
}
</style>
